<?php

namespace app\admin\controller;

use app\BaseController;

use app\common\model\FileModel;

use app\common\model\FileCategoryModel;

use Qiniu\Auth;

class File extends BaseController
{
    // 资源列表
    public function list()
    {
        $keyword = $this->request->param('keyword/s','');
        $category_id = $this->request->param('category_id/d',0);//分类
        $file_type = $this->request->param('file_type/d',0);//类型 0-全部 1-图片 2-视频 3-文档

        $where=[
            ['firm_id','=',$this->request->firm_id],
            ['is_delete','=',0]
        ];
        if(!empty($category_id)){
            $where[] = ['category_id','=',$category_id];
        }
        if(!empty($file_type)){
            $where[] = ['file_type','=',$file_type];
        }
        if(!empty($keyword)){
            $where[] = ['file_name','LIKE','%'.$keyword.'%'];
        }

        $list = FileModel::where($where)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order('file_id','desc')
            ->select();

        $total = FileModel::where($where)->count('file_id');
        return success([
            'list' => $list,
            'total' => $total
        ]);
    }
    public function upload(){
        $category_id = $this->request->param('category_id/d',0);//分类
        $form_type = $this->request->param('form_type/s','admin');//来源
        if(empty($_FILES['file'])){
            return error('请上传文件');
        }
        $file_name = $_FILES['file']['name'];//获取缓存区图片,格式不能变
        $size = filesize($_FILES['file']['tmp_name']);
        $ext = explode(".", $file_name);//拆分获取图片名
        $ext = strtolower($ext[count($ext) - 1]);

        $dir = root_path().'/public';
        $path = '/upload/'.$this->request->firm_id.'/';
        
        if($ext == 'jpg' || $ext == 'png' || $ext == 'gif'){
            $path .= 'image/';
            $file_type = 1;
            if ($size > 2*1024*1024){
                return error('图片最大支持2M');
            }
        }elseif($ext == 'mp4'){
            $file_type = 2;
            $path .= 'video/';
            if ($size > 100*1024*1024){
                return error('视频最大支持100M');
            }
        }elseif($ext == 'pdf'){
            $file_type = 3;
            $path .= 'pdf/';
            if ($size > 15*1024*1024){
                return error('文档最大支持15M');
            }
        }elseif($ext == 'mp3'){
            $file_type = 1;
            $path .= 'audio/';
            if ($size > 5*1024*1024){
                return error('音频最大支持5M');
            }
        }else{
            return error('文件格式错误');
        }
        // 检查目录是否存在
        if (!is_dir($dir.$path)) {
            // 目录不存在，创建目录
            if (!mkdir($dir.$path, 0755, true)){
                return error('目录创建失败');
            }
        }
        $file_url = $path.md5(uniqid(true)).time().'.'.$ext;
        move_uploaded_file($_FILES['file']['tmp_name'], $dir.$file_url);
        $fileModel = new FileModel();
        $fileModel->category_id = $category_id;
        $fileModel->form_type = $form_type;
        $fileModel->file_type = $file_type;
        $fileModel->file_name = $file_name;
        $fileModel->url = 'https://mp.xhm.net'.$file_url;
        $fileModel->size = $size;
        $fileModel->ext = $ext;
        $fileModel->firm_id = $this->request->firm_id;
        $fileModel->account_id = $this->request->account_id;
        $fileModel->save();
        return  success('上传成功');
    }
    // 添加/修改资源
    public function save()
    {
        $file_id = $this->request->param('file_id/d',0);
        $category_id = $this->request->param('category_id/d',0);//分类
       
        $file_name = $this->request->param('file_name/s','');//资源名称

        
        if($file_id > 0){
            if(null === $fileModel = FileModel::find($file_id)){
                return error('资源不存在');
            }
            $fileModel->category_id = $category_id;
            $fileModel->file_name = $file_name;
            if($fileModel->save()){
                return  success('修改成功');
            }else{
                return error('修改失败');
            }
        }else{
             $form_type = $this->request->param('form_type/s','admin');//来源
            $file_type = $this->request->param('file_type/d',0);//类型 0-全部 1-图片 2-视频 3-文档
            $hash = $this->request->param('hash/s','');
            $key = $this->request->param('key/s','');
            $url = $this->request->param('url/s','');
    
            $size = $this->request->param('size/d',0);
            $ext = $this->request->param('ext/s','');
        
            $fileModel = new FileModel();
            $fileModel->category_id = $category_id;
            $fileModel->firm_id = $this->request->firm_id;
            $fileModel->form_type = $form_type;
            
            $fileModel->file_type = $file_type;
            $fileModel->file_name = $file_name;
            $fileModel->hash = $hash;
            $fileModel->key = $key;
            $fileModel->url = 'https://file.mp.xhm.net/'.$url;
            $fileModel->size = $size;
            $fileModel->ext = $ext;
            // $fileModel->firm = $this->request->firm_id;
            $fileModel->account_id = $this->request->account_id;
            if($fileModel->save()){
                return  success('上传成功');
            }else{
                return error('上传失败');
            }
        }
    }
    // 删除资源
    public function delete(){
        $file_id = $this->request->param('file_id/d',0);
        if(empty($file_id)){
            return error('错误操作');
        }
        if(null === $fileModel = FileModel::find($file_id)){
            return error('文章不存在');
        }
        if($fileModel->firm_id != $this->request->firm_id){
            return error('没有权限');
        }
        $fileModel->is_delete = 1;
        $fileModel->save();
        return success('删除成功');
    }
    // 分类列表
    public function categoryList()
    {
        $keyword = $this->request->param('keyword/s','');
        $where=[
            ['firm_id','=',$this->request->firm_id]
        ];
        if(!empty($keyword)){
            $where[] = ['category_name','LIKE','%'.$keyword.'%'];
        }
        $list = FileCategoryModel::where($where)
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order('sort','desc')
            ->select();
        $total = FileCategoryModel::where($where)->count('category_id');
        return success([
            'list' => $list,
            'total' => $total
        ]);
    }
    // 全部分类
    public function categoryAllList()
    {
        $keyword = $this->request->param('keyword/s','');
        $where = [
            ['firm_id','=',$this->request->firm_id]
        ];
        if(!empty($keyword)){
            $where[] = ['category_name','LIKE','%'.$keyword.'%'];
        }
        $list = FileCategoryModel::field('category_name,category_id,sort')->where($where)
            ->order('sort','desc')
            ->select();
        return success($list);
    }

    public function categorySave(){
        $category_id = $this->request->param('category_id/d',0);
        $category_name = $this->request->param('category_name/s','');
        $sort = $this->request->param('sort/d',0);

        if(empty($category_name)){
            return error('请填写分类名称');
        }

        if(empty($category_id)) {
            $category = new FileCategoryModel();
            $category->firm_id = $this->request->firm_id;
        }else{
            if(null === $category = FileCategoryModel::find($category_id))  return error('不存在');
            if($category->firm_id != $this->request->firm_id)  return error('不存在');
        }

        $category->category_name = $category_name;
        $category->sort = $sort;

        $category->save();

        return success('保存成功');
    }

    public function categoryDetele(){
        $category_id = $this->request->param('category_id/d',0);

        if(null === $category = FileCategoryModel::find($category_id))  return error('不存在');

        if($category->firm_id != $this->request->firm_id){
            return error('没有权限');
        }
        $category->is_delete = 1;
        $category->save();
        return $this->success('删除成功');
    }

    public function qiniuToken(){
        $ak =  env('Qiniu_ak', '');
        $sk =  env('Qiniu_sk', '');
        $bucket =  env('Qiniu_bucket', '');
        $auth = new Auth(trim($ak), trim($sk));
        $token = $auth->uploadToken(trim($bucket));
        return success($token);
    }
}
